<template>
  <div>
  <!--      搜索框-->
  <div style="min-height: 100px;margin:0 10px; padding:10px 10px;background: white" class="search-div">
    <a-form ref="searchFormRef" name="advanced_search" class="ant-advanced-search-form"
            :model="searchFormState" @finish="searchDataSource">
      <!--                搜索框-->
      <a-row :gutter="24">
        <template v-for="(searchColumnItem,index) in ExperimentSearchColumns" :key="index">
          <a-col v-show="searchExpand || index <= 5" :span="4">
            <a-form-item v-if="searchColumnItem.inputType=='input'"
                         :name="searchColumnItem.name"
                         :label="searchColumnItem.label"
                         :rules="[{ required: false }]"
            >
              <a-input v-model:value="searchFormState[searchColumnItem.name]" :placeholder="searchColumnItem.placeHolder || '请输出值'"></a-input>
            </a-form-item>
          </a-col>
        </template>
      </a-row>
      <!--               -->
      <a-row>
        <a-col :span="24" style="text-align: right">
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button style="margin: 0 8px" @click="() => searchFormRef.resetFields()">重置</a-button>
        </a-col>
      </a-row>

    </a-form>
  </div>
  </div>
<div>
  <div class="form-div" style="margin:10px;padding:5px;background: white;">
    <!--          表单区域-->
    <a-table   v-model:dataSource="tableDataSource" :columns="experimentAddTableColumns" v-model:pagination="pagination">
      <template #bodyCell="{ column, record }">
<!--        操作列-->
        <template v-if="column.key==='action'&& record.status === '未排课'">
          <a-button @click="openCheckModel(record)">排课</a-button>
        </template>
      </template>
    </a-table>
  </div>

  <!-- 修改状态的模态框 -->
  <a-modal width="1000px" v-model:visible="statusModalVisible" title="排课" @ok="handleStatusSubmit" @cancel="statusModalVisible = false" ok-text="驳回申请" cancel-text="取消">
<!--    from-->
    <a-form
        :model="modelShowFormState"
        v-bind="{
            labelCol: { span: 3 },
            wrapperCol: { span: 16 },}"
        name="nest-messages">
      <a-form-item v-for="{key,title,inputType} in modelShowFormField" :key="key" :name="[key]" :label="title"  >
        <template v-if="inputType === 'disableType'">
          <a-input v-model:value="modelShowFormState[key]" :disabled="true"/>
        </template>
      </a-form-item>
    </a-form>

<!--    表单-->
    <a-table  v-model:dataSource="modelLabDataSource" :columns="modelLabColumns">
      <template #bodyCell="{ column, record }">
        <!--        操作列-->
        <template v-if="column.key==='action'">
          <a-button @click="addSchedule(record)">选择该实验室</a-button>
        </template>
      </template>
    </a-table>
  </a-modal>
</div>
</template>

<script lang="ts" setup>
import {experimentAddTableColumns, ExperimentSearchColumns,modelLabColumns,modelLabDataSource} from "./experimentcheck.data";
import {onMounted, reactive, ref} from "vue";
import {RepairSearchColumns} from "@/views/equipmentRepair/check/equipmentRepairCheck.data";
import type {FormInstance} from "ant-design-vue";
import {addLabSchedule, list, rejectApp, selectLabs} from "./experimentCheck.api";
import {userTableColumns} from "@/views/user/user.data";
import {message} from "ant-design-vue";

//model展示数据的表头
const modelShowFormField=[
  {
    title:"课程名字",
    key: 'courseName',
    inputType: 'disableType'
  },
  {
    title:"教师",
    key: 'teacherName',
    inputType: 'disableType'
  },
  {
    title:"学期",
    key: 'semesterName',
    inputType: 'disableType'
  },
  {
    title:"实验室类型",
    key: 'labTypeName',
    inputType: 'disableType'
  },
  {
    title:"班级名称",
    key: 'classname',
    inputType: 'disableType'
  },
  {
    title:"学生人数",
    key: 'studentCount',
    inputType: 'disableType'
  },
  {
    title:"开始周",
    key: 'startWeek',
    inputType: 'disableType'
  },
  {
    title:"结束周",
    key: 'endWeek',
    inputType: 'disableType'
  },
  {
    title:"上课时间（周）",
    key: 'weekdayName',
    inputType: 'disableType'
  },
  {
    title:"上课时间（节次）",
    key: 'sectionName',
    inputType: 'disableType'
  },
  {
    title:"状态",
    key: 'status',
    inputType: 'disableType'
  },
]
/**
 * Model展示申请的数据
 */
const modelShowFormState=reactive({})


//表单数据
const tableDataSource = reactive([])
// 分页配置
const pagination=reactive( {
  pageSize: 10, // 每页显示的条数
  showSizeChanger: true, // 是否可以改变每页显示的条数
  pageSizeOptions: ['10', '20', '30', '40'], // 可选的每页显示条数
  showQuickJumper: true, // 是否可以快速跳转到指定页
  showTotal: total => `共 ${total} 条`, // 显示总条数和当前数据范围
  current: 1, // 当前页数
  total:0, // 总条数
  onChange: null // 页码改变时的回调函数,稍后才将器填充进来
})
//保存搜索的信息
const searchFormState = reactive({});
// 搜索框收起
const searchExpand = ref(false);
//重置效果
const searchFormRef = ref<FormInstance>()
// 记录当前选中的记录
const selectedRecord = ref(null);
// 是否显示修改状态的模态框
let statusModalVisible = ref(false);
//选择的实验室
const selectedLab=ref()
//空闲的实验室
const availableLabs=reactive({})

/**
 * 更新表单函数
 * @param param
 */
const reloadForm=async ()=>{
  const {code,message,data} =  await list(searchFormState,{pageNo:pagination.current,pageSize:pagination.pageSize});
  console.log(data)
  if(data!=null){
    const {records,current,total}= data
    //更新页面数据
    const totalPages = total/pagination.pageSize+1
    if(totalPages<current){
      pagination.current = 1
      await  reloadForm()
      return //阻止执行下面代码
    }
    pagination.total=total
    // 添加新记录到响应式数组
    tableDataSource.length=0
    records.forEach(record => {
      tableDataSource.push(record);
    });

  }
}

const searchDataSource = (values: any) => {
  reloadForm()
};

/**
 * 进来数据加载
 */
onMounted(async () => {
  pagination.onChange=handlePageChang
  await reloadForm();

})
/**
 * 更换页码信息的时候显示
 * @param page
 * @param pageSize
 */
const handlePageChang=(page, pageSize)=>{//参数为改变后的页码和页码数量
  pagination.current=page
  pagination.pageSize=pageSize
  reloadForm()
}
// 点击修改状态按钮，显示修改状态的模态框，并保存选中的记录
const openCheckModel=async (record)=>{
  console.log(record)
  //配置数据项目
  Object.keys(modelShowFormState).forEach(key => {
    modelShowFormState[key] = ''; // 或者其他适当的初始值，如null或默认值
  });
  Object.assign(modelShowFormState,record)
  //发送数据，并且请求要求返回list集合
  try{
    const {code,message:labResultMessage,data} = await selectLabs({},{id:record.id})
    if(code==200){
      modelLabDataSource.length=0
      data.forEach((labItem)=>{
        modelLabDataSource.push(labItem)
      })
    }
  }catch{
    message.error("获取空闲数据列失败")
  }


  statusModalVisible.value=true
}
/**
 * 接受拿到
 */
const addSchedule = async (record) => {
  console.log("RECORD",record);
  //labId
  console.log("RECORD",record.id);
  //申请
  console.log("modelShowFormState",modelShowFormState.id);
  const schedule = {
    labId: record.id,
    experimentApplicationId: modelShowFormState.id
  };
  console.log("schedule ", schedule);
  try{
    await addLabSchedule(schedule);
  }catch (error){
    message.error("新增labSchedule失败")
  }
  statusModalVisible.value=false;
  reloadForm()
}
const handleStatusSubmit = async () => {
  console.log("申请",modelShowFormState.id);
  try {
    // 假设 currentRecordId 是在组件的 data 中定义的，用于存储当前记录的 ID
    await rejectApp({},{ id:modelShowFormState.id });

    statusModalVisible.value = false;

  } catch (error) {
    // 捕获并处理任何异常错误
    console.error(error);
  }
  reloadForm()

};
</script>
